<template>
  <div>
    <el-drawer
      append-to-body
      :wrapper-closable="false"
      :visible.sync="drawerVisible"
      size="80%"
      @close="close"
    >
      <template slot="title">
        回复邮件
      </template>
      <el-container style="margin: 20px;">
        <el-row style="width: 100%" :gutter="20">
          <el-col :xs="24" :sm="24" :md="18" :lg="18" :xl="18">
            <el-row>
              <div style="display: inline-block; margin-bottom: 10px">{{ mailbox_data.subject }}
                <el-tag v-if="mailbox_data.process_label && mailbox_data.process_label.length" size="mini" @click="handleEditLabel">{{ mailbox_data.process_label }}</el-tag>
                <el-button type="primary" icon="el-icon-edit" title="修改标签" size="mini" @click="handleEditLabel">标签</el-button>
                <el-button v-if="!mailbox_data.crmcustomer_id" :loading="aiLoading" type="primary" icon="el-icon-user-solid" title="添加客户" size="mini" @click="handleAddCustomer">添加客户</el-button>
                <div v-else>
                  <el-button v-if="orders.length === 0" type="success" icon="el-icon-s-goods" title="新增询盘订单" size="mini" @click="handleAddCRMOrder">添加为询盘订单</el-button>
                  <el-button type="danger" icon="el-icon-delete" title="取消绑定" size="mini" @click="handleDeleteCustomer">取消绑定</el-button>

                </div>
                <el-select
                  v-model="mailbox_data.processor_id"
                  placeholder="指定处理人"
                  filterable
                  clearable
                  @change="handleChangeManager(mailbox_data)"
                >
                  <el-option
                    v-for="user in users"
                    :key="user.id"
                    :label="user.show_name"
                    :value="user.id"
                  />
                </el-select>

              </div>
              <el-row style="display: inline-block; float: right;margin-bottom: 10px;">
                <el-button type="text" @click="isEditing=true;activeNames=[];">简单回复</el-button>
                <el-button type="text" @click="handlShowHtmlReplay">HTML回复</el-button>
              </el-row>
              <el-row>
                <div style="display: block;color:#5e5e5e;font-size: .75rem" class="mobile-hidden">
                  <span>来自:</span><span>{{ mailbox_data.mail_from }}</span><span>发送给: </span><span sty>{{ mailbox_data.mail_to }}</span><span style="float: right;"><i class="el-icon-time" />{{ mailbox_data.mail_date }}</span>
                </div>
                <el-divider />
                <iframe v-if="mailbox_data.content_type === 'text/html'" ref="iframe" style="border: none; max-height: 400px;" :src="iframeSrc" width="100%" height="400" />
                <div v-else style="display: inline-block;background-color: aliceblue;"><pre style="overflow: scroll;white-space: pre-wrap;">{{ body }}</pre></div>
              </el-row>
            </el-row>
            <el-row v-if="mailbox_data.attachments !== undefined">
              <div v-for="(item, index) in mailbox_data.attachments" :key="index" style="display: inline-block;">
                <!-- Image files -->
                <a v-if="item.content_type.indexOf('image') !== -1" :href="item.url" target="_blank">
                  <el-image :src="item.url" :preview-src-list="[item.url]" style="width: auto; height: 50px;" />
                </a>
                <!-- PDF files -->
                <a v-else-if="item.content_type.indexOf('pdf') !== -1" :href="item.url" target="_blank">
                  <!-- PDF icon SVG -->
                  <svg style="width:32px;height:32px" viewBox="0 0 24 24">
                    <path fill="currentColor" d="M14,2H6A2,2 0 0,0 4,4V20A2,2 0 0,0 6,22H18A2,2 0 0,0 20,20V8L14,2M16,15H9V13H16V15M16,11H9V9H16V11M14,7V3.5L18.5,8H15A1,1 0 0,1 14,7Z" />
                  </svg>
                </a>
                <!-- Excel files -->
                <a v-else-if="item.content_type.indexOf('excel') !== -1 || item.content_type.indexOf('spreadsheetml') !== -1" :href="item.url" target="_blank">
                  <!-- Excel icon SVG -->
                  <svg style="width:32px;height:32px" viewBox="0 0 24 24">
                    <path fill="currentColor" d="M19,3A2,2 0 0,1 21,5V19A2,2 0 0,1 19,21H5A2,2 0 0,1 3,19V5A2,2 0 0,1 5,3H19M17,17H12V15H17V17M17,13H12V11H17V13M7,9V11.5H9.5L7,17V9M17,9H12V7H17V9M5,9V7H7V17H5V15H3V17A2,2 0 0,0 5,19H19A2,2 0 0,0 21,17V7A2,2 0 0,0 19,5H5A2,2 0 0,0 3,7V9H5Z" />
                  </svg>
                </a>
                <!-- Word documents -->
                <a v-else-if="item.content_type.indexOf('word') !== -1 || item.content_type.indexOf('documentml') !== -1" :href="item.url" target="_blank">
                  <!-- Word icon SVG -->
                  <svg style="width:32px;height:32px" viewBox="0 0 24 24">
                    <path fill="currentColor" d="M19,3A2,2 0 0,1 21,5V19A2,2 0 0,1 19,21H5A2,2 0 0,1 3,19V5A2,2 0 0,1 5,3H19M17,17H12V15H17V17M17,13H12V11H17V13M7,9V11.5H9.5L7,17V9M17,9H12V7H17V9M5,9V7H7V17H5V15H3V17A2,2 0 0,0 5,19H19A2,2 0 0,0 21,17V7A2,2 0 0,0 19,5H5A2,2 0 0,0 3,7V9H5Z" />
                  </svg>
                </a>
                <!-- Text files -->
                <a v-else-if="item.content_type.indexOf('text') !== -1" :href="item.url" target="_blank">
                  <!-- Text icon SVG -->
                  <svg style="width:32px;height:32px" viewBox="0 0 24 24">
                    <path fill="currentColor" d="M13,9H11V7H13M13,13H11V11H13M13,17H11V15H13M17,2A2,2 0 0,1 19,4V20A2,2 0 0,1 17,22H7A2,2 0 0,1 5,20V4A2,2 0 0,1 7,2H17M17,7L15,5H9L7,7H17Z" />
                  </svg>
                </a>
                <!-- Other file types -->
                <a v-else :href="item.url" target="_blank">
                  <!-- Default file icon -->
                  <i class="el-icon-files" :title="item.filename" style="font-size: 32px; color: red" />
                </a>
              </div>

            </el-row>
            <el-divider />
            <el-row :style="{ display: isEditing ? 'block' : 'none' }">
              主题:<el-input v-model="replyemail.subject" />
              <div style="display: block; margin-top: 5px;" />
              内容:<el-input v-model="replyemail.text_content" type="textarea" :rows="8" />
              <el-button v-if="this.body !== null" type="text" @click="handlePreMail">引用邮件内容</el-button>
              <el-button @click="isEditing = false; sendMailloading=false;">取 消</el-button>
              <el-button type="success" style="float: right" :loading="sendMailloading" @click="handleSendMail">发 送</el-button>
            </el-row>
            <el-row>
              <el-button icon="el-icon-delete" size="mini" style="float: right" type="danger" @click="handleDeleteMail">删除邮件</el-button>
            </el-row>
          </el-col>
          <el-col :xs="24" :sm="24" :md="6" :lg="6" :xl="6">
            <crmcustomerinfocard :customer_id="mailbox_data.crmcustomer_id" @get-customer="handleReponseCustomer" />
          </el-col>
        </el-row>

      </el-container>
    </el-drawer>
    <el-dialog :visible.sync="showDetailVisible" title="写邮件" width="960px" :close-on-click-modal="false" @close="handleCloseMail">
      <div style="display: block;">
        主 题:<el-input v-model="replyemail.subject" />
      </div>
      <div style="display: block;">
        收件人:<el-input v-model="replyemail.mail_to" />
      </div>
      <div style="display: block;">
        发件人:
        <el-autocomplete
          v-model="replyemail.mail_from"
          class="inline-input"
          :fetch-suggestions="querySearchMail"
          placeholder="请输入发件箱"
        />
      </div>
      <div style="display: block; margin-top: 5px;" />
      <!--       <tinymce ref="mt" :height="300" v-model="replyemail.body"></tinymce>-->
      <crmtinymce ref="mt" v-model="replyemail.body" :height="300" app="email" />
      <el-button v-if="this.body !== null" type="text" @click="handlePreMail">引用邮件内容</el-button>
      <el-select v-if="prompts.length" v-model="prompt_id" size="mini" placeholder="请选择PROMPT">
        <el-option
          v-for="item in prompts"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        />
      </el-select>
      <el-button v-if="this.body !== null && prompt_id !== ''" :loading="aiLoading" type="text" @click="handleAiReplay">AI回复</el-button>
      <!--        <el-button type="success" @click="handleSendMail" style="float: right">发 送</el-button>-->
      <span slot="footer" class="dialog-footer">
        <el-button @click="showDetailVisible = false; sendMailloading=false;">取 消</el-button>
        <el-button type="primary" :loading="sendMailloading" @click="handleSendMail">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="邮件标签" :visible.sync="labelDialogVisible">
      <el-select v-model="mailbox_data.process_label" placeholder="系统标签" @change="handleChangeMailLabel">
        <el-option v-for="item in tags" :key="item.tag_name" :label="item.tag_name" :value="item.tag_name" />
      </el-select>
      <el-input v-model="mailbox_data.process_label" clearable placeholder="自定义标签" />
      <div slot="footer" class="dialog-footer">
        <el-button @click="labelDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleChangeMailLabel">保 存</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="showMialBodyVisible" title="查看邮件内容" width="1080px">
      <div style="display: block;">
        主 题:<el-input v-model="showmail.subject" />
      </div>
      <div style="display: block;">
        收件人:<el-input v-model="showmail.mail_to" />
      </div>
      <div style="display: block; margin-top: 5px;" />
      <crmtinymce ref="showmailty" v-model="showmail.body" :height="300" />
      <span slot="footer" class="dialog-footer">
        <el-button @click="showMialBodyVisible = false;">取 消</el-button>
      </span>
    </el-dialog>
    <crmeditcustomer
      :customer_row="customer_temp"
      doaction="create"
      :is-visible="addCustomerVisible"
      @close="handleEditCustomerSuccess"
    />
    <crmneworder
      :crmcustomer_id="mailbox_data.crmcustomer_id"
      :mailbox_data="mailbox_data"
      :is-visible="newOrderVisible"
      @close="newOrderVisible=false"
    />
  </div>
</template>

<script>
import { Put, GetBody, CRMSendMail, GetBindMails } from '@/api/crm/crmmailbox'
import { AIReplyEmail, AIGetPrompts } from '@/api/crm/crmai'
import { Get as GetRemark, Post as PostRemark, Get as GetTags } from '@/api/crm/crmm'
import { CRMGetProjectUsers as GetUsers } from '@/api/crm/crmmanage'
// 获取邮箱账号列表
import { Get as GetMailAccount } from '@/api/crm/crmmailserverconfig'
import qs from 'qs'
import crmtinymce from '@/components/CRMTinymce'
import ScrollPane from '../../../components/ScrollPane'
import { countries, customer_source, getCountryLabel } from '../../../api/crm/crmcommon'
import Crmeditcustomer from './crmeditcustomer'
import Crmneworder from './crmneworder'
import Crmcustomerinfocard from './crmcustomerinfocard'
import { Post as GetAiContent } from '@/api/cms/openai'

export default {
  name: 'Crmsendmail',
  components: { Crmcustomerinfocard, Crmneworder, Crmeditcustomer, ScrollPane, crmtinymce },
  props: ['mailbox_data', 'isVisible', 'newMailDialogShow'],
  data() {
    return {
      ownersLoading: false,
      users: [],
      extract_data: '',
      drawerWidth: '50%', // 默认宽度
      prompts: [],
      prompt_id: '',
      aiLoading: false,
      mailAccounts: [],
      newOrderVisible: false,
      countries: countries,
      customer_source: customer_source,
      getCountryLabel: getCountryLabel,
      customer_temp: {
        name: '', // The name of the customer
        company: '', // The company name of the customer
        domain: '', // Domain name associated with the customer
        mail: '', // Email address of the customer
        phone: '', // Phone number of the customer
        tag: [],
        note: '',
        whatsapp: '', // WhatsApp number of the customer
        country: '', // Country of the customer
        source: '独立站', // Source from where the customer was acquired
        address: '' // Physical address of the customer
      },
      addCustomerVisible: false,
      attachments: [],
      orders: [],
      remarks: [],
      inputRows: 1,
      remark_temp: {
        table_name: 'CRMRemark',
        content: '',
        next_follow_up_time: ''
      },
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now()
        },
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', new Date())
          }
        }, {
          text: '3天后',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() + 3600 * 1000 * 24 * 3)
            picker.$emit('pick', date)
          }
        }, {
          text: '一周后',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() + 3600 * 1000 * 24 * 7)
            picker.$emit('pick', date)
          }
        }]
      },
      attachments_label: '附件列表',
      showMialBodyVisible: false,
      showAll: false, // 默认不显示所有数据，只显示最后的5条
      labelDialogVisible: false,
      showDetailVisible: false,
      sendMailloading: false,
      current_mail: {
        subject: '',
        iframeSrc: ''
      },
      data: [],
      activeNames: [],
      drawerVisible: false,
      iframeSrc: '',
      isEditing: false,
      showmail: {
        mailbox_id: '',
        text_content: '',
        body: '',
        subject: '',
        msc_id: '',
        mail_from: '',
        mail_to: ''
      },
      replyemail: {
        mailbox_id: '',
        text_content: '',
        body: '',
        subject: '',
        msc_id: '', // 邮件发送账号id
        mail_from: '',
        mail_to: ''
      },
      body: null,
      projectUsers: [],
      listLoading: false,
      tags: []
    }
  },
  computed: {
    shownData() {
    // 如果 showAll 为 true 或者数据项不超过5条，返回所有数据
      if (this.showAll || this.data.length <= 5) {
        return this.data
      } else {
      // 否则，只返回最后5条数据
        return this.data.slice(-5)
      }
    }
  },
  watch: {

    newMailDialogShow(v) {
      if (v) {
        this.showDetailVisible = true
        this.replyemail.subject = ''
        this.replyemail.mail_to = ''
        this.replyemail.mail_from = ''
        this.replyemail.mailbox_id = ''
        this.$refs.mt.setContent('')
        this.$nextTick(() => {
          if (this.$refs.mt) {
            this.$refs.mt.initTinymce()
          }
        })
        this.isEditing = false
      }
    },
    isVisible(v) {
      this.drawerVisible = v
      this.remarks = []
      console.log('is visible')
      if (v && this.mailbox_data && this.mailbox_data.mail_token) {
        this.replyemail.subject = this.mailbox_data.subject
        this.replyemail.mail_to = this.mailbox_data.mail_from
        this.replyemail.mail_from = this.mailbox_data.mail_to
        this.replyemail.mailbox_id = this.mailbox_data.id
        this.$nextTick(() => {
          if (this.$refs.mt) {
            this.$refs.mt.initTinymce()
            this.$refs.mt.setContent('')
          }
        })
        this.isEditing = false
        this.data = []
        this.activeNames = []
        this.fetchEmailBody()
        this.handleMailReaded()
      }
    }
  },
  created() {
    this.handleGetTags()
    this.handleFetchGetUsers()
    this.handleGetMailAccounts()
    this.handleGetAIPrompts()
  },
  methods: {
    handleFetchGetUsers() {
      this.ownersLoading = true
      GetUsers(null, qs.stringify({ 'is_active': 1 }))
        .then(response => {
          this.ownersLoading = false
          this.users = response.data.data
        })
        .catch(e => {
          this.ownersLoading = false
        })
    },
    handleEditCustomerSuccess() {
      this.addCustomerVisible = false
      if (this.customer_temp.id !== undefined) {
        console.log('set customer_id')
        this.handleEditMail('crmcustomer_id', this.customer_temp.id)
        this.mailbox_data.crmcustomer_id = this.customer_temp.id
      }
    },
    handleGetAiContent(quote) {
      let prompt = '我会跟给你客户询盘信息，你帮我提取客户名字，电话，国家代码，客户询盘内容，邮箱\n' +
        '我的要求是：\n' +
        '1. 必须用json输出，我可以直接用python代码提取json数据\n' +
        '2.不要额外任何输出,只输出大括号内容，不要添加引号或者json等markdown语法\n' +
        '示例数据:\n' +
        '{\n' +
        '  "name": "Trina Mo",\n' +
        '  "phone": "21367123",\n' +
        '  "country": "China",\n' +
        '  "message": "Test",\n' +
        '  "email": "234782@qq.com"\n' +
        '}\n' +
        '询盘信息如下:\n'
      prompt += quote
      this.aiLoading = true
      GetAiContent({ prompt: prompt, engine: 'gpt-4o', aiprompt_id: '', keywords: [] })
        .then(response => {
          // console.log(response.content)
          console.log(response.content)
          const doc = new DOMParser().parseFromString(response.content, 'text/html')
          const t2 = JSON.parse(doc.body.textContent)
          console.log(t2)
          // 如果t2是一个对象
          if (t2 && typeof t2 === 'object') {
            this.customer_temp.note = t2.message
            this.customer_temp.phone = t2.phone
            if (t2.phone && t2.phone[0] === '+') {
              t2.phone = t2.phone.slice(1)
            }
            this.customer_temp.whatsapp = t2.phone + '@c.us'
            // 如果第一个符号是+，则去掉
            this.customer_temp.country = t2.country
            if (this.customer_temp.country) {
              const f = countries.find(item => item.name.toLowerCase() === t2.country.toLowerCase())
              this.customer_temp.country = f ? f.code : ''
            }
            this.customer_temp.mail = t2.email
            this.customer_temp.name = t2.name
          }
          this.addCustomerVisible = true
          this.aiLoading = false
        }).catch(e => {
          console.log('error')
          this.addCustomerVisible = true
          this.aiLoading = false
        })
    },
    handleGetAIPrompts() {
      AIGetPrompts({ t: 'email_prompt' }).then(response => {
        this.prompts = response.data
      }).catch(err => {
        console.log(err)
      })
    },
    handleGetMailAccounts() {
      GetMailAccount(null, qs.stringify({
        page: 1,
        ac: 1,
        pagesize: 100
      })).then(response => {
        this.mailAccounts = response.data.data.map(item => ({
          value: item.username,
          label: item.username
        }))
      }).catch(err => {
        console.log(err)
      })
    },
    querySearchMail(queryString, cb) {
      const emails = this.mailAccounts
      const results = queryString ? emails.filter(this.createFilter(queryString)) : emails
      // 调用 callback 返回建议列表的数据
      // 设置恢复邮箱账号为第一个默认选项
      if (results.length > 0) {
        this.replyemail.mail_from = results[0].value
      }
      cb(results)
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
      }
    },
    handleFocus() {
      this.inputRows = 4 // 获得焦点时行数变为4
    },
    handleBlur() {
      if (this.remark_temp.content === '') {
        this.inputRows = 1 // 失去焦点且内容为空时行数重置为1
      }
    },
    handleCloseMail() {
      this.$emit('closeMailDialog', true)
    },
    handleReponseCustomer(data) {
      this.mailbox_data.customer = data
      // 获取customer的orders 如果存在该属性
      if (data.orders) {
        this.orders = data.orders
      }
    },
    handleSaveRemark() {
      if (this.mailbox_data.crmcustomer_id) {
        this.remark_temp.crmcustomer_id = this.mailbox_data.crmcustomer_id
        PostRemark(this.remark_temp).then(response => {
          this.notify('添加成功')
          this.handleGetRemarks()
        })
      }
    },
    handleGetTags() {
      GetTags(null, qs.stringify({
        table_name: 'CRMTag',
        page: 1,
        app: 'mail',
        pagesize: 100
      })).then(response => {
        this.tags = response.data.data
        console.log(this.tags)
      }).catch(err => {
        console.log(err)
      })
    },
    handleGetRemarks() {
      this.remarks = []
      GetRemark(null, qs.stringify({
        table_name: 'CRMRemark',
        crmcustomer_id: this.mailbox_data.crmcustomer_id,
        page: 1,
        pagesize: 100
      })).then(response => {
        this.remarks = response.data.data
      }).catch(err => {
        console.log(err)
      })
    },
    handleShowMail(mail) {
      this.showmail = mail
      this.showMialBodyVisible = true
      this.$nextTick(() => {
        if (this.$refs.showmailty) {
          this.$refs.showmailty.initTinymce()
          this.$refs.showmailty.setContent(mail.body)
        }
      })
    },
    goFullScreen(index) {
      const iframe = this.$refs.iframe[index] // 通过索引访问特定的iframe（如果有多个）
      if (iframe) {
        if (iframe.requestFullscreen) {
          iframe.requestFullscreen()
        } else if (iframe.mozRequestFullScreen) { /* Firefox */
          iframe.mozRequestFullScreen()
        } else if (iframe.webkitRequestFullscreen) { /* Chrome, Safari & Opera */
          iframe.webkitRequestFullscreen()
        } else if (iframe.msRequestFullscreen) { /* IE/Edge */
          iframe.msRequestFullscreen()
        }
      }
    },
    makeURLBlob(content) {
      const fullHtmlContent = `<!DOCTYPE html><html><body  style="background-color: aliceblue;">${content}</body></html>`

      // 创建一个Blob对象，类型为"text/html"
      const blob = new Blob([fullHtmlContent], { type: 'text/html' })
      // 创建一个指向该Blob的URL
      return URL.createObjectURL(blob)
    },
    showMailDetail(mail) {
      this.current_mail = mail
      this.showDetailVisible = true
    },
    fetchEmailBody() {
      console.log('fetchmailboxy')
      this.body = null
      GetBody(qs.stringify({
        mail_token: this.mailbox_data.mail_token
      }))
        .then(response => {
          // 确保response是字符串形式的HTML内容
          // 或者如果response是一个对象，你可能需要 response.data 或类似的属性
          // 添加缺失的DOCTYPE声明、<html>、<body>标签
          this.body = response
          const fullHtmlContent = `<!DOCTYPE html><html><body style="background-color: aliceblue;">${response}</body></html>`

          // 创建一个Blob对象，类型为"text/html"
          const blob = new Blob([fullHtmlContent], { type: 'text/html' })
          // 创建一个指向该Blob的URL
          this.iframeSrc = URL.createObjectURL(blob)
        }).catch(err => {
          console.log(err)
        })
    },
    handleGetBindMails() {
      this.listLoading = true
      this.attachments = []
      this.attachments_label = '附件列表'
      GetBindMails({ mail_token: this.mailbox_data.mail_token })
        .then(response => {
          // this.data.map(item => ({
          //   ...item,
          //   iframeSrc: this.makeURLBlob(item.body)
          // }));
          this.data = response.data.data.map(m => {
            this.$set(m, 'iframeSrc', this.makeURLBlob(m.body))
            // 如果不存在，则将其推入 this.attachments 数组
            if (m.attachments) {
              m.attachments.forEach(att => {
                if (!this.attachments.find(attachment => attachment.id === m.id)) {
                  this.attachments.push(att)
                }
              })
            }

            return m
          })
          this.data = this.data.reverse()
          this.listLoading = false
          this.total = response.data.total
          this.data.forEach(item => {
            // 检查当前元素的 mail_token 是否与 this.mailbox_data.mail_token 相等
            if (item.mail_token === this.mailbox_data.mail_token) {
              this.body = item.body
              this.iframeSrc = item.iframeSrc
            }
          })
          this.attachments_label = '附件列表(' + this.attachments.length.toString() + ')'
        }).catch(err => {
          console.log(err)
          this.listLoading = false
        })
    },
    handleAiReplay() {
      this.replyemail.body = ''
      this.$nextTick(() => {
        if (this.$refs.mt && this.$refs.mt.hasInit) {
          this.$refs.mt.setContent(this.replyemail.body)
        }
      })
      this.aiLoading = true
      AIReplyEmail({ prompt_id: this.prompt_id, mailbox_id: this.mailbox_data.id }).then(response => {
        this.aiLoading = false
        this.replyemail.body = response.data
        this.$nextTick(() => {
          if (this.$refs.mt && this.$refs.mt.hasInit) {
            this.$refs.mt.setContent(this.replyemail.body)
          }
        })
      }).catch(err => {
        console.log(err)
      })
    },
    handlePreMail() {
      // body添加 pre 内容
      this.replyemail.body = this.body
      this.replyemail.body = "&nbsp;&nbsp;<br>---Original--=<br><div style='display:block'>" + this.replyemail.body + '</div>'
      this.$nextTick(() => {
        if (this.$refs.mt && this.$refs.mt.hasInit) {
          this.$refs.mt.setContent(this.replyemail.body)
        }
      })

      this.replyemail.subject = 'Re:' + this.mailbox_data.subject
    },
    extractNameAndEmail(str) {
      // 正则表达式匹配 "<邮箱>" 结构，捕获邮箱地址
      const regex = /^(.*?)\s*<?([^<>]+@[^<>]+)>?$/
      const match = str.match(regex)

      if (match) {
        // 如果匹配到，第一个捕获组是名称（可能为空），第二个捕获组是邮箱
        return {
          name: match[1].trim(), // 去除名称前后的空格
          email: match[2] // 邮箱地址
        }
      } else {
        // 如果没有匹配到，返回空字符串
        return {
          name: '',
          email: ''
        }
      }
    },
    extractCustomerInquiryInfo(text) {
      this.handleGetAiContent(text)
      // 正则表达式匹配不同字段
      const phoneRegex = /(\(\d{3}\)\s*\d{3}-\d{4})|(\d{3}-\d{3}-\d{4})|(\d{10})/g
      const firstNameRegex = /FirstName:\s*([\s\S]+?)(?=\n|$)/i
      const lastNameRegex = /LastName:\s*([\s\S]+?)(?=\n|$)/i
      const emailRegex = /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g
      const countryRegex = /国家:\s*([\s\S]+?)(?=\n|$)/i

      // 提取信息
      const phoneMatch = text.match(phoneRegex)
      const firstNameMatch = text.match(firstNameRegex)
      const lastNameMatch = text.match(lastNameRegex)
      const emailMatch = text.match(emailRegex)
      const countryMatch = text.match(countryRegex)
      // 组装信息
      // 组装信息，如果匹配结果不为 null，则调用 trim() 方法；否则返回空字符串
      const phone = phoneMatch ? phoneMatch[0].trim() : ''
      const firstName = firstNameMatch && firstNameMatch[1] ? firstNameMatch[1].trim() : ''
      const lastName = lastNameMatch && lastNameMatch[1] ? lastNameMatch[1].trim() : ''
      const email = emailMatch ? emailMatch[0].trim() : ''
      const country = countryMatch ? countryMatch[1].trim() : ''

      const name = `${firstName} ${lastName}`.trim()

      return { phone, name, email, country }
    },
    handleDeleteCustomer() {
      this.handleEditMail('crmcustomer_id', null)
      this.mailbox_data.crmcustomer_id = null
    },
    handleAddCRMOrder() {
      this.newOrderVisible = true
    },
    extractPlainText(html) {
    // Create a new div element
      const tempDiv = document.createElement('div')
      // Set the HTML content
      tempDiv.innerHTML = html
      // Get the text content
      let text = tempDiv.textContent || tempDiv.innerText || ''
      // Decode HTML entities
      text = text.replace(/&nbsp;/g, ' ')
      text = text.replace(/&amp;/g, '&')
      text = text.replace(/&lt;/g, '<')
      text = text.replace(/&gt;/g, '>')
      // Remove extra whitespace
      text = text.replace(/\s+/g, ' ').trim()
      return text
    },
    handleAddCustomer() {
      // const t = this.extractNameAndEmail(this.mailbox_data.mail_from)
      this.customer_temp = {
        name: '', // The name of the customer
        company: '', // The company name of the customer
        domain: '', // Domain name associated with the customer
        mail: '', // Email address of the customer
        phone: '', // Phone number of the customer
        tag: [],
        note: '',
        whatsapp: '', // WhatsApp number of the customer
        country: '', // Country of the customer
        source: '独立站', // Source from where the customer was acquired
        address: '' // Physical address of the customer
      }
      this.customer_temp.tag = ['初步询盘']
      this.customer_temp.note = this.extractPlainText(this.body)
      // 如果存在id属性则删除
      console.log(this.customer_temp.note)
      // if (this.body && this.body.indexOf('FirstName') !== -1) {
      this.handleGetAiContent(this.body)
      // } else {
      //   this.addCustomerVisible = true;
      // }
      //   const t2 = this.extractCustomerInquiryInfo(this.body)
      //   this.customer_temp.phone = t2.phone
      //   this.customer_temp.whatsapp = t2.phone
      //   this.customer_temp.country = t2.country
      //   if (this.customer_temp.country) {
      //     const f = countries.find(item => item.name.toLowerCase() === t2.country.toLowerCase())
      //     this.customer_temp.country = f ? f.code : ''
      //   }
      //   this.customer_temp.mail = t2.email || t.email
      //   this.customer_temp.name = t2.name || t.name
      // } else {
      //   this.customer_temp.mail = t.email
      //   this.customer_temp.name = this.mailbox_data.short_from
      // }
    },
    handleEditLabel() {
      this.labelDialogVisible = true
      // this.$prompt('请输入标签', '提示', {
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消'
      // }).then(({ value }) => {
      //   this.$message({
      //     type: 'success',
      //     message: '你的标签是: ' + value
      //   });
      // }).catch(() => {
      //   this.$message({
      //     type: 'info',
      //     message: '取消输入'
      //   });
      // });
    },
    handleChangeMailLabel() {
      this.handleEditMail('process_label', this.mailbox_data.process_label)
      this.labelDialogVisible = false
    },
    handleMailReaded() {
      if (!this.mailbox_data.readed) {
        this.mailbox_data.readed = true
        this.handleEditMail('readed', true)
      }
    },
    handleEditMail(label, value) {
      Put(this.mailbox_data.id, {
        [label]: value
      })
    },
    handleChangeManager(data) {
      Put(this.mailbox_data.id, {
        processor_id: data.processor_id
      })
    },
    handlShowHtmlReplay() {
      this.showDetailVisible = true
      this.isEditing = false
      // 检查customer.mail是否存在
      if (this.mailbox_data.customer && this.mailbox_data.customer.mail) {
        this.replyemail.mail_to = this.mailbox_data.customer.mail
      }
      this.replyemail.text_content = ''
    },
    handleDeleteMail() {
      this.$confirm(`确认要删除邮件吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.handleEditMail('showAble', false)
        this.$emit('delete', this.mailbox_data.id)
        this.drawerVisible = false
      }).catch(() => {
      })
    },
    handleSendMail() {
      this.sendMailloading = true
      CRMSendMail(this.replyemail).then(response => {
        console.log(response.msg)
        this.sendMailloading = false
        this.notify(response.msg)
        this.showDetailVisible = false
      }).catch(err => {
        console.log(err)
        this.sendMailloading = false
      })
    },
    close() {
      this.$nextTick(() => {
        if (this.$refs.mt) {
          this.$refs.mt.destroyTinymce()
        }
      })
      this.$emit('close')
    },
    notify(message, duration) {
      this.$notify({
        title: '成功',
        message: message,
        type: 'success',
        duration: duration || 2000
      })
    }
  }
}
</script>

<style>
.el-form-item--medium .el-form-item__content, .el-form-item--medium .el-form-item__label
{
  line-height: 1px;
}
</style>

<style scoped>
.top >>>  .el-form-item--medium .el-form-item__content, .el-form-item--medium .el-form-item__label
{
  line-height: 1px;
}
.el-tag + .el-tag {
  margin-left: 10px;
}
.top >>> .sortable-ghost{
  opacity: .8;
  color: #fff!important;
  background: #42b983!important;
}
.top >>> .el-select .el-input {
  width: 350px;
}

.top >>> .input-with-select .el-input-group__prepend {
  background-color: #fff;
}

.top {
  padding-left: 20px;
  margin-bottom: 30px;
  margin-top: 28px;
}

.input-with-select {
  width: calc(100% - 200px);
}

.add-btn {
  float: right;
  margin-right: 20px;
  width: 150px
}

.mt-pagination {
  float: right;
  margin-top: 5px;
}

.app-container >>> .el-dialog {
  margin-top: 48px !important;
  margin-bottom: 68px;
}

.mt-dialog >>> .el-transfer-panel {
  width: calc(50% - 60px);
}

.mt-form >>> .el-select {
  width: 100%;
}

.mt-form >>> .el-input__inner {
  width: 100%;
}

.mt-dialog >>> .el-dialog {
  margin-top: 60px;
  /*margin: 168px auto !important;*/
}

.mt-dialog >>> .el-dialog__body {
  padding-bottom: 100px;
}

@media (max-width: 768px) {
  .mobile-hidden {
    display: none;
  }
  /* 响应式调整布局和元素尺寸 */
  .el-col, .el-row {
    width: 100% !important;
    margin-bottom: 10px;
  }

  .el-container, .el-input, .el-select {
    width: 100% !important;
  }

  /* 简化表单元素，例如减少边距和填充 */
  .el-form-item {
    margin-bottom: 8px;
  }

  /* 隐藏或调整非关键按钮和标签 */
  .el-button[title="修改标签"], .el-button[title="添加客户"], .el-button[title="新增询盘订单"] {
    display: none;
  }

  /* 优化邮件正文的显示 */
  iframe, pre {
    width: 100% !important;
    height: auto !important;
    max-height: 300px; /* 调整高度以适应屏幕 */
    overflow: scroll; /* 允许滚动 */
  }

  /* 优化附件显示 */
  [v-for="item in mailbox_data.attachments"] {
    display: inline-block;
    width: 100%;
    text-align: center; /* 居中显示 */
  }

  /* 优化回复表单的显示 */
  .reply-form {
    display: block; /* 默认显示简单回复表单 */
  }
}

</style>
